package com.lzs.kunei.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.lzs.entity.*;
import com.lzs.kucun.service.StockService;
import com.lzs.kunei.service.AllocationDetailService;
import com.lzs.kunei.service.AllocationService;
import com.lzs.util.JwtUtils;
import com.lzs.util.R;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.xml.bind.annotation.W3CDomHandler;
import java.util.Date;
import java.util.List;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author wpy
 * @since 2020-11-24
 */
@ApiModel(value = "调拨")
@RestController
@RequestMapping("/kunei/allocation")
public class AllocationController {
    @Autowired
    private AllocationService allocationService;
    @Autowired
    private StockService stockService;
    @Autowired
    private AllocationDetailService allocationDetailService;

    @PostMapping("/selectAllocationPage/{current}/{size}")
    public R selectPutonPage(@PathVariable Integer current, @PathVariable Integer size, @RequestBody Allocation allocation,HttpServletRequest request) {
        Page<Allocation> allocationPage = null;
        try {
            String warehouseId = request.getHeader("warehouseId");
            String[] warehouseid = warehouseId.split(",");
            allocationPage = allocationService.selectAllocationPage(current, size, allocation,warehouseid);

            return R.ok().message("查询成功").data("allocationPage", allocationPage);
        } catch (RuntimeException e) {
            e.printStackTrace();
            return R.error().message("查询出错").data("allocationPage", allocationPage);
        }
    }

    @ApiOperation(value = "添加移库数据")
    @PostMapping("/addAllocation")
    public R addAllocation(@RequestBody Allocation allocation, HttpServletRequest request) {
        try {
            String token=request.getHeader("token");
            Long userid= JwtUtils.getMemberIdByJwtToken(token);
            User user=stockService.selectUser(userid);
            String name = user.getName();
            Long bwarehouseid = allocation.getBwarehouseid();
            Long awarehouseid = allocation.getAwarehouseid();
            Warehouse bwarehouse = stockService.selectWarehouse(bwarehouseid);
            Warehouse awarehouse = stockService.selectWarehouse(awarehouseid);
            allocation.setAwarehousename(awarehouse.getName());
            allocation.setBwarehousename(bwarehouse.getName());
            allocation.setState("0");
            allocation.setCreateid(userid);
            allocation.setCreator(name);
            allocation.setUpdateid(userid);
            allocation.setUpdator(name);
            allocationService.save(allocation);
            return R.ok().message("添加移库成功");
        } catch (RuntimeException e) {
            e.printStackTrace();
            return R.error().message("添加移库失败");
        }
    }

    @ApiOperation(value = "删除调拨订单")
    @DeleteMapping("/deleteById")
    public R deleteById(@RequestBody Allocation allocation) {
        Long id = allocation.getId();
        try {
            allocationService.removeById(id);
            return R.ok().message("删除成功");
        } catch (RuntimeException e) {
            e.printStackTrace();
            return R.error().message("删除失败");
        }
    }

    @ApiOperation(value = "点录入明细后的回显,原仓库框默认赋值，目标仓库默认赋值")
    @PostMapping("/allocationById")
    public R allocationById(@RequestBody AllocationDetail allocation) {
        try {
            System.out.println(allocation.toString());
            Long id = allocation.getId();
            Allocation allocation1 = allocationService.getById(id);
            return R.ok().message("回显成功").data("allocation", allocation1);
        } catch (RuntimeException e) {
            e.printStackTrace();
            return R.error().message("回显失败");
        }

    }

    /**
     * @param allocation
     * @return key:
     * locatorcode:新仓库货位下拉
     * oldlocatorcode:旧仓库货位下拉
     * commoditybars：商品编码下拉
     */
    @ApiOperation(value = "录入明细中货位根据仓库id下拉，7529")
    @PostMapping("seletByWid")
    public R selectByWid(@RequestBody AllocationDetail allocation) {
        Long bwarehouseid = allocation.getBwarehouseid();
        Long awarehouseid = allocation.getAwarehouseid();
        //调用仓库的接口，参数仓库id

        String locatorcode = allocation.getLocatorcode();
        String oldlocatorcode = allocation.getOldlocatorcode();
        R r = stockService.selectCommoditybar(oldlocatorcode, bwarehouseid);
        return r.data("locatorcode", "新仓库货位下拉").data("oldlocatorcode", "旧仓库货位下拉");
    }

    @ApiOperation(value = "结束修改状态")
    @PostMapping("/endState")
    public R endState(@RequestBody Allocation allocation,HttpServletRequest request) {
        try {
            String token=request.getHeader("token");
            Long userid= JwtUtils.getMemberIdByJwtToken(token);
            User user=stockService.selectUser(userid);
            String name = user.getName();
            String allocationno = allocation.getAllocationno();
            QueryWrapper<AllocationDetail> queryWrapper1=new QueryWrapper<>();
            queryWrapper1.eq("allocationno",allocationno);
            List<AllocationDetail> list = allocationDetailService.list(queryWrapper1);
            if (list==null||list.size()==0){
                return R.error().message("未录入商品，请录入再结束");
            }
            QueryWrapper<Allocation> allocationQueryWrapper = new QueryWrapper<>();
            allocationQueryWrapper.eq("allocationno", allocationno);
            Allocation allocation1 = new Allocation();
            allocation1.setUpdateid(userid);
            allocation1.setUpdator(name);
            allocation1.setState("1");
            allocationService.update(allocation1, allocationQueryWrapper);
            return R.ok().message("修改审核中状态成功");
        } catch (RuntimeException e) {
            return R.error().message("修改审核中状态失败");
        }
    }

    @ApiOperation(value = "取消审核")
    @PostMapping("/cancelAudit")
    public R cancelAudit(@RequestBody List<Allocation> list,HttpServletRequest request) {
        try {
            String token=request.getHeader("token");
            Long userid= JwtUtils.getMemberIdByJwtToken(token);
            User user=stockService.selectUser(userid);
            String name = user.getName();
            int k = 1;
            for (int i = 0; i < list.size(); i++) {
                Allocation allocation = list.get(i);
                if (!allocation.getState().equals("2")) {
                    return R.error().message("存在未审核的订单,或者已调拨的订单,请重新选择");
                }
            }
            for (int i = 0; i < list.size(); i++) {
                Allocation allocation = list.get(i);
                String allocationno = allocation.getAllocationno();
                Long bwarehouseid = allocation.getBwarehouseid();
                QueryWrapper<AllocationDetail> queryWrapper = new QueryWrapper<>();
                queryWrapper.eq("allocationno", allocationno);
                List<AllocationDetail> list2 = allocationDetailService.list(queryWrapper);
                for (int j = 0; j < list2.size(); j++) {
                    AllocationDetail detail = list2.get(j);
                    Integer qty = detail.getQty();
                    String commoditybar = detail.getCommoditybar();
                    String locatorcode = detail.getLocatorcode();
                    stockService.updateLqtyCQuantity(locatorcode, commoditybar, bwarehouseid, qty);
                }
                Allocation allocation1 = new Allocation();
                allocation1.setState("0");
                allocation1.setUpdateid(userid);
                allocation1.setUpdator(name);
                QueryWrapper<Allocation> queryWrapper1 = new QueryWrapper<>();
                queryWrapper.eq("allocationno", allocationno);
                allocationService.update(allocation1, queryWrapper1);
            }
                return R.ok().message("取消审核成功");

        } catch (RuntimeException e) {
            e.printStackTrace();
            return R.error().message("取消审核出错");
        }
    }

    /*
    @ApiOperation(value = "审核")
    @PostMapping("/updateAudit")
    public R updateAudit(@RequestBody  List<Allocation> list){
        try {
            for (int i = 0; i < list.size(); i++) {
                Allocation allocation = list.get(i);
                if (!allocation.getState().equals("1")) {
                    return R.error().message("存在通过审核的订单,或者不可用的订单,请重新选择");
                }
            }
            for (int i = 0; i < list.size(); i++) {
                Allocation allocation = list.get(i);
                String allocationno = allocation.getAllocationno();
                QueryWrapper<AllocationDetail> queryWrapper = new QueryWrapper<>();
                queryWrapper.eq("allocationno", allocationno);
                List<AllocationDetail> list2 = allocationDetailService.list(queryWrapper);
                for (int j = 0; j < list2.size(); j++) {
                    AllocationDetail detail = list2.get(j);
                    Integer qty = detail.getQty();
                    Long awarehouseid = detail.getAwarehouseid();
                    Long bwarehouseid = detail.getBwarehouseid();
                    String commoditybar = detail.getCommoditybar();
                    String locatorcode = detail.getLocatorcode();
                    String oldlocatorcode = detail.getOldlocatorcode();
                    stockService.updateLqtyQuantity(oldlocatorcode, commoditybar, bwarehouseid, qty);
                    Boolean b = stockService.selectIsExit(locatorcode, commoditybar, awarehouseid);
                    if (!b) {
                        String allocationno1 = detail.getAllocationno();
                        Stock stock = new Stock();
                        stock.setBillno(allocationno1);
                        stock.setWarehouseid(awarehouseid);
                        stock.setCqty(qty);
                        stock.setLqty(0);
                        stock.setUqty(qty);
                        BeanUtils.copyProperties(detail, stock);
                        stockService.save(stock);
                    } else {
                        stockService.updateAllQuantity(locatorcode, commoditybar, awarehouseid, qty);
                    }
                }
                Allocation allocation1=new Allocation();
                allocation1.setState("2");
                QueryWrapper<Allocation> queryWrapper1=new QueryWrapper<>();
                queryWrapper.eq("allocationno",allocationno);
                allocationService.update(allocation1,queryWrapper1);
            }
            return R.ok().message("审核成功");
        }catch (RuntimeException e){
            e.printStackTrace();
            return R.error().message("审核出错");
        }

    }

     */

    @ApiOperation(value = "审核")
    @PostMapping("/updateAudit")
    public R updateAudit(@RequestBody List<Allocation> list,HttpServletRequest request) {
        try {
            String token=request.getHeader("token");
            Long userid= JwtUtils.getMemberIdByJwtToken(token);
            User user=stockService.selectUser(userid);
            String name = user.getName();

            for (int i = 0; i < list.size(); i++) {
                Allocation allocation = list.get(i);
                if (!allocation.getState().equals("1")) {
                    return R.error().message("存在通过审核的订单,或者已调拨的订单,请重新选择");
                }
            }
            for (int i = 0; i < list.size(); i++) {
                Allocation allocation = list.get(i);
                String allocationno = allocation.getAllocationno();
                Long bwarehouseid = allocation.getBwarehouseid();
                QueryWrapper<AllocationDetail> queryWrapper = new QueryWrapper<>();
                queryWrapper.eq("allocationno", allocationno);
                List<AllocationDetail> list2 = allocationDetailService.list(queryWrapper);
                for (int j = 0; j < list2.size(); j++) {
                    AllocationDetail detail = list2.get(j);
                    Integer qty = detail.getQty();
                    String commoditybar = detail.getCommoditybar();
                    String locatorcode = detail.getLocatorcode();
                    stockService.updateLqtyQuantity(locatorcode, commoditybar, bwarehouseid, qty);
                }
                Allocation allocation1 = new Allocation();
                allocation1.setState("2");
                allocation1.setAuditid(userid);
                allocation1.setAuditor(name);
                allocation1.setUpdateid(userid);
                allocation1.setUpdator(name);
                allocation1.setAudittime(new Date());
                QueryWrapper<Allocation> queryWrapper1 = new QueryWrapper<>();
                queryWrapper1.eq("allocationno", allocationno);
                allocationService.update(allocation1, queryWrapper1);
            }
            return R.ok().message("审核成功");
        } catch (RuntimeException e) {
            e.printStackTrace();
            return R.error().message("审核出错");
        }


    }
}

